﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
using System.IO;
using System.Text.RegularExpressions;

namespace QuanLyNhapXuat.Presentation.WinForm
{
    public partial class frmGiaoHang : Telerik.WinControls.UI.RadForm
    {
        private static frmGiaoHang doituong = null;
        public static frmGiaoHang TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmGiaoHang();
            return doituong;
        }        
        public frmGiaoHang()
        {
            InitializeComponent();            
        }
        //them service chi tiet giao hang
        QuanLyNhapXuat.SR_ChiTietGiaoHang.WS_ChitietgiaohangSoapClient xl_CTSoGiao = new QuanLyNhapXuat.SR_ChiTietGiaoHang.WS_ChitietgiaohangSoapClient();
        //them service khach hang
        QuanLyNhapXuat.RS_XuLiKhachHang.WS_KhachHangSoapClient xl_KhachHang = new QuanLyNhapXuat.RS_XuLiKhachHang.WS_KhachHangSoapClient();       
        //them service so nhap
        QuanLyNhapXuat.SR_SoNhap.WS_SoNhapSoapClient xl_SoNhap = new QuanLyNhapXuat.SR_SoNhap.WS_SoNhapSoapClient();
        //Them service so giao
        QuanLyNhapXuat.SR_SoGiao.WS_SoGiaoSoapClient xl_SoGiao = new QuanLyNhapXuat.SR_SoGiao.WS_SoGiaoSoapClient();

        DataSet dsKhachHang = new DataSet();
        DataSet dsNhapHang = new DataSet();
        
        DataSet dsGiaoHang_Theo_MaKH = new DataSet();
        DataSet dsCTSoNhap_Theo_MaSN = new DataSet();

        DataTable bang_KhachHang = new DataTable();
        DataTable bang_SoNhap = new DataTable();
        public int kich_loadDSKH = 0;
        public string MaNV;      
        private void frmGiaoHang_Load(object sender, EventArgs e)
        {            
            //Load danh sach Khach hang
            Load_DSKhachHang();
            //Load danh sach so nhap
            Load_DSSoNhap();

            dtp_ngaygiao.Value = DateTime.Today;

            //Khoi tao cac control
            KhoiTaoControl(false);            
        }
        private void KhoiTaoControl(bool DieuKien)
        {
            GroupBox_ThongTinGiaoHang.Enabled = DieuKien;
            btn_luu.Enabled = DieuKien;
            btn_Xoagiaohang.Enabled = DieuKien;
            btn_XuatBuHang.Enabled = DieuKien;
        }
        private void Load_DSSoNhap()
        {
            try
            {               
                dsNhapHang.Clear();
                for (int i = 0; i < bang_KhachHang.Rows.Count; i++)
                {                    
                    dsNhapHang.ReadXml(new StringReader(xl_SoNhap.LayDS_SoNhapChuaGiao_TheoMaKH(int.Parse(bang_KhachHang.Rows[i]["MaKH"].ToString()))));
                    if (dsNhapHang.Tables.Count > 0)
                    {
                        bang_SoNhap = dsNhapHang.Tables[0];
                    }
                }
                mccb_maphieunhap.DataSource = bang_SoNhap;
                mccb_maphieunhap.DisplayMember = "MaSN";
                mccb_maphieunhap.ValueMember = "MaSN";
                mccb_maphieunhap.SelectedIndex = -1;
                FilterDescriptor des_sn = new FilterDescriptor(this.mccb_maphieunhap.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mccb_maphieunhap.EditorControl.FilterDescriptors.Add(des_sn);
            }
            catch (Exception ex) { }
        }

        private void Load_DSKhachHang()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mccb_khachhang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                dsKhachHang.ReadXml(new StringReader(xl_KhachHang.layds()));
                bang_KhachHang = dsKhachHang.Tables[0];
                mccb_khachhang.DataSource = bang_KhachHang;
                mccb_khachhang.DisplayMember = "tenkh";
                mccb_khachhang.ValueMember = "makh";
                mccb_khachhang.SelectedIndex = -1;
                FilterDescriptor des_kh = new FilterDescriptor(this.mccb_khachhang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mccb_khachhang.EditorControl.FilterDescriptors.Add(des_kh);
            }
            catch (Exception ex) {}
        }

        private void btn_xuathang_Click(object sender, EventArgs e)
        {
            frmXuatBu frm_xuatbu = new frmXuatBu();
            frm_xuatbu.Show();
        }
        private string xulymaGiao()
        {
            DataSet tam = new DataSet();
            DateTime ngaygiao = dtp_ngaygiao.Value;
            string chuoi = "SG" + ngaygiao.Day.ToString("00") + ngaygiao.Month.ToString("00") + ngaygiao.Year.ToString();
            tam.ReadXml(new StringReader(xl_SoNhap.SelectSQL("select top 1 masg from sogiao where masg like '" + chuoi + "%' order by masg desc")));
            string mamoi;
            if (tam.Tables.Count == 0)
                mamoi = chuoi + "0001";
            else
            {
                string matam = tam.Tables[0].Rows[0][0].ToString();
                string kituso = matam.Substring(10, 5).ToString();
                int somoi = int.Parse(kituso) + 1;
                mamoi = chuoi + somoi.ToString("0000");
            }
            return mamoi;
        }
        private void btn_luu_Click(object sender, EventArgs e)
        {                        
            if (gridview_KetQua.Rows.Count > 0)
            {
                DateTime ngaygiao = dtp_ngaygiao.Value;
                string masg = xulymaGiao();
                for (int i = 0; i < gridview_KetQua.Rows.Count; i++)
                {                    
                    try
                    {
                        if (gridview_KetQua.Rows[i].Cells["ngayGiao"].Value != null)
                        {
                            xl_SoGiao.Them(masg, int.Parse(mccb_khachhang.SelectedValue.ToString()), MaNV, DateTime.Parse(gridview_KetQua.Rows[i].Cells["ngayGiao"].Value.ToString()));
                            if (gridview_KetQua.Rows[i].Cells["SoLuongGiao"].Value != null)
                            {
                                string mamh = gridview_KetQua.Rows[i].Cells["MaMH"].Value.ToString();
                                string mawash = gridview_KetQua.Rows[i].Cells["MaWash"].Value.ToString();
                                int soluonggiao = int.Parse(gridview_KetQua.Rows[i].Cells["SoLuongGiao"].Value.ToString());
                                decimal thanhtien = decimal.Parse(gridview_KetQua.Rows[i].Cells["ThanhTien"].Value.ToString());
                                string ghichu = gridview_KetQua.Rows[i].Cells["GhiChu"].Value.ToString();
                                xl_CTSoGiao.them(masg, mamh, mawash, soluonggiao, thanhtien, ghichu);

                                MessageBox.Show("Lưu Thành Công.\nVui lòng chọn 'Sổ Nhập' kế tiếp", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                mccb_maphieunhap.EditorControl.Rows.RemoveAt(mccb_maphieunhap.SelectedIndex);
                                gridview_KetQua.DataSource = null;
                                mccb_khachhang.SelectedIndex = -1;
                                mccb_maphieunhap.Text = "";                                
                                XoaTrang_ThongTinGiaoHang();
                                KhoiTaoControl(false);
                                mccb_maphieunhap.Focus();
                            }
                            else
                            {
                                MessageBox.Show("Bạn phải nhập 'Số Lượng Giao' để 'Lưu'", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Bạn phải chọn 'Ngày Giao' để 'Lưu'","Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    catch (Exception) { }
                }                
            }
        }

        private void mccb_maphieunhap_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mccb_maphieunhap.SelectedIndex != -1 && mccb_khachhang.SelectedIndex != -1)
            {
                try
                {
                    dsCTSoNhap_Theo_MaSN.Clear();
                    dsCTSoNhap_Theo_MaSN.ReadXml(new StringReader(xl_SoNhap.LayDSCTSoNhap_Theo_MaSN(mccb_maphieunhap.SelectedValue.ToString().Trim())));
                    if (dsCTSoNhap_Theo_MaSN.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < dsCTSoNhap_Theo_MaSN.Tables[0].Rows.Count; i++)
                        {
                            if (dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"].ToString().Contains(".0000") == true)
                            {
                                dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"] = dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"].ToString().Replace(".0000", "");
                                dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["NgayNhap"] = DateTime.Parse(dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["NgayNhap"].ToString()).ToShortDateString();
                            }                            
                        }
                        gridview_KetQua.DataSource = dsCTSoNhap_Theo_MaSN.Tables[0];
                        mccb_khachhang.EditorControl.Rows[int.Parse(mccb_maphieunhap.EditorControl.CurrentRow.Cells["MaKH"].Value.ToString()) - 1].IsCurrent = true;                        
                    }
                }
                catch (Exception) { } 
            }
        }

        private void mccb_khachhang_SelectedIndexChanged(object sender, EventArgs e)
        {            
            if ((mccb_khachhang.SelectedIndex > 0 && mccb_maphieunhap.SelectedIndex == 0) || kt == true)
                Load_Data_CTSoGiao();
        }

        private void Load_Data_CTSoGiao()
        {
            DataSet tam = new DataSet();
            DataTable bang_Tam = new DataTable();
            try
            {
                tam.ReadXml(new StringReader(xl_KhachHang.LayDS_CTNhapXuat_Theo_MaKH(int.Parse(mccb_khachhang.SelectedValue.ToString()))));
                if (tam.Tables.Count > 0)
                {
                    for (int i = 0; i < tam.Tables[0].Rows.Count; i++)
                    {
                        if (tam.Tables[0].Rows[i]["SoLuongGiao"].ToString() == tam.Tables[0].Rows[i]["SoLuongNhap"].ToString())
                            tam.Tables[0].Rows[i].Delete();
                    }
                    bang_Tam = tam.Tables[0];

                    for (int i = 0; i < bang_Tam.Rows.Count; i++)
                    {
                        if (bang_Tam.Rows[i]["DonGiaNhap"].ToString().Contains(".0000") == true)
                        {
                            bang_Tam.Rows[i]["DonGiaNhap"] = bang_Tam.Rows[i]["DonGiaNhap"].ToString().Replace(".0000", "");
                            bang_Tam.Rows[i]["ThanhTien"] = bang_Tam.Rows[i]["ThanhTien"].ToString().Replace(".0000", "");
                        }
                    }
                    gridview_KetQua.DataSource = bang_Tam;
                    btn_XuatBuHang.Enabled = true;
                }
                else
                    gridview_KetQua.DataSource = null;
            }
            catch (Exception) { }
        }

        private void btn_xacnhan_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (gridview_KetQua.Rows.Count > 0)
            {
                DateTime ngaygiao = dtp_ngaygiao.Value;
                int soluonggiao = int.Parse(up_soluonggiao.Value.ToString());
                decimal dongianhap = decimal.Parse(gridview_KetQua.CurrentRow.Cells["DonGiaNhap"].Value.ToString());
                string ghichu = txt_Ghichu.Text;
                if (ngaygiao < DateTime.Parse(gridview_KetQua.CurrentRow.Cells["NgayNhap"].Value.ToString()))
                {
                    errorProvider1.SetError(dtp_ngaygiao, "Bạn phải chọn 'Ngày Giao' lớn hơn 'Ngày Nhập' trong lưới.\nVui lòng chọn lại 'Ngày Giao'");
                    return;
                }
                if (up_soluonggiao.Value <= decimal.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongNhap"].Value.ToString()))
                {
                    if (up_soluonggiao.Value < decimal.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongNhap"].Value.ToString()))
                    {
                        ghichu = "Thiếu " + (int.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongNhap"].Value.ToString()) - soluonggiao);
                    }
                    gridview_KetQua.CurrentRow.Cells["NgayGiao"].Value = ngaygiao.ToShortDateString();
                    gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value = soluonggiao;
                    gridview_KetQua.CurrentRow.Cells["GhiChu"].Value = ghichu;
                    gridview_KetQua.CurrentRow.Cells["ThanhTien"].Value = soluonggiao * dongianhap;
                    //Chon dong so luong giao = null     
                    try
                    {
                        for (int i = 0; i < gridview_KetQua.RowCount; i++)
                        {
                            if (gridview_KetQua.Rows[i].Cells["SoLuongGiao"].Value == null)
                            {                                
                                gridview_KetQua.Rows[i].IsCurrent = true;                                
                                up_soluonggiao.Focus();
                                return;
                            }
                        }
                    }
                    catch (Exception) { }
                    btn_luu.Enabled = true;
                    btn_Xoagiaohang.Enabled = true;
                }
                else
                {
                    MessageBox.Show("Số lượng giao lớn hơn số lượng nhập. \nVui lòng chọn lại số lượng giao nhỏ hơn hoặc bằng số lượng nhập", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void btn_Dong_Click(object sender, EventArgs e)
        {
            this.Close();
            kichhoat = false;
        }
        
        private void btn_XuatBuHang_Click(object sender, EventArgs e)
        {
            frmXuatBu xuatbu = new frmXuatBu();
            xuatbu.SoLuongNhap = int.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongNhap"].Value.ToString());
            xuatbu.SoLuongGiao = int.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value.ToString());
            xuatbu.MaMH = gridview_KetQua.CurrentRow.Cells["MaMH"].Value.ToString();
            xuatbu.MaWash = gridview_KetQua.CurrentRow.Cells["MaWash"].Value.ToString();
            xuatbu.DonGiaNhap = decimal.Parse(gridview_KetQua.CurrentRow.Cells["DonGiaNhap"].Value.ToString());
            xuatbu.GhiChu = gridview_KetQua.CurrentRow.Cells["GhiChu"].Value.ToString();
            xuatbu.MaSG = gridview_KetQua.CurrentRow.Cells["MaSG"].Value.ToString();
            xuatbu.ShowDialog();
            //Load lai Data chi tiet so giao
            Load_Data_CTSoGiao();
        }

        private void btn_Xoagiaohang_Click(object sender, EventArgs e)
        {
            //Xoá hàng có 2 trường hợp xảy ra:
            //+ Nếu xóa Hàng ma chua co trong CSDL nhu sau:
            if (gridview_KetQua.Rows.Count > 0)
            {
                gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value = "";
                gridview_KetQua.CurrentRow.Cells["NgayGiao"].Value = "";
                gridview_KetQua.CurrentRow.Cells["GhiChu"].Value = "";
                gridview_KetQua.CurrentRow.Cells["ThanhTien"].Value = "";
                XoaTrang_ThongTinGiaoHang();
            }
            //+ Da co trong CSDL thi phai Update lai Trang Thai = 0 hoac 1 de Xoa Tam Thoi
        }       
        
        private void gridview_KetQua_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
        {
            try
            {
                if (e.CurrentRow.Index != -1 && gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value != null && gridview_KetQua.CurrentRow.Cells["NgayGiao"].Value != null)
                {
                    dtp_ngaygiao.Text = gridview_KetQua.CurrentRow.Cells["NgayGiao"].Value.ToString();
                    if (gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value != null)
                        up_soluonggiao.Value = decimal.Parse(gridview_KetQua.CurrentRow.Cells["SoLuongGiao"].Value.ToString());
                    txt_Ghichu.Text = gridview_KetQua.CurrentRow.Cells["GhiChu"].Value.ToString();                    
                }
            }
            catch (Exception) { }             
        }
        
        private bool kt = false;
        private void mccb_maphieunhap_Leave(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (mccb_maphieunhap.Text.Trim() != "")
            {
                if (Regex.IsMatch(mccb_maphieunhap.Text, @"^(SN)|(sn)\d{13}$") == true)
                {
                    mccb_khachhang.EditorControl.Rows[int.Parse(mccb_maphieunhap.EditorControl.CurrentRow.Cells["MaKH"].Value.ToString()) - 1].IsCurrent = true;                    
                }
                else
                {
                    errorProvider1.SetError(mccb_maphieunhap, "Nhập sai 'Mã Sổ Nhập'. \n Vui lòng nhập lại.\nVí dụ: 'SN290520110001','sn290520110002' ... ");                    
                    mccb_maphieunhap.Focus();
                }
            }
            else
                kt = true;
        }

        private void mccb_khachhang_Leave(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (mccb_khachhang.Text.Trim() != "" && Regex.IsMatch(mccb_khachhang.Text,@"^[^0-9]\w[^0-9]+$") == false)
            {
                errorProvider1.SetError(mccb_khachhang, "'Tên Khách Hàng' không có số. \n Vui lòng nhập lại.\nVí dụ: Nam,Thành ...");                
                mccb_khachhang.Focus();                
            }
            else
                XoaTrang_ThongTinGiaoHang();
        }

        private void mccb_maphieunhap_KeyPress(object sender, KeyPressEventArgs e)
        {            
            if(e.KeyChar == '\r')            
            {
                if (mccb_maphieunhap.Text.Trim() != "")
                {
                    errorProvider1.Clear();
                    try
                    {
                        dsCTSoNhap_Theo_MaSN.Clear();
                        dsCTSoNhap_Theo_MaSN.ReadXml(new StringReader(xl_SoNhap.LayDSCTSoNhap_Theo_MaSN(mccb_maphieunhap.SelectedValue.ToString().Trim())));                        
                        if (dsCTSoNhap_Theo_MaSN.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < dsCTSoNhap_Theo_MaSN.Tables[0].Rows.Count; i++)
                            {
                                if (dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"].ToString().Contains(".0000") == true)
                                {
                                    dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"] = dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["DonGiaNhap"].ToString().Replace(".0000", "");
                                    dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["NgayNhap"] = DateTime.Parse(dsCTSoNhap_Theo_MaSN.Tables[0].Rows[i]["NgayNhap"].ToString()).ToShortDateString();                                    
                                }                                
                            }
                            gridview_KetQua.DataSource = dsCTSoNhap_Theo_MaSN.Tables[0];
                            mccb_khachhang.EditorControl.Rows[int.Parse(mccb_maphieunhap.EditorControl.CurrentRow.Cells["MaKH"].Value.ToString()) - 1].IsCurrent = true;
                            
                            GroupBox_ThongTinGiaoHang.Enabled = true;                            
                        }
                    }
                    catch (Exception ex) { }                    
                }
                else
                {
                    mccb_khachhang.Text = "";
                    gridview_KetQua.DataSource = null;
                }
            }
        }

        private void btn_XoaTrang_Click(object sender, EventArgs e)
        {
            XoaTrang_ThongTinGiaoHang();
        }

        private void XoaTrang_ThongTinGiaoHang()
        {
            dtp_ngaygiao.Value = DateTime.Today;
            up_soluonggiao.Value = 1;
            txt_Ghichu.Text = "";
        }

        private void dtp_ngaygiao_Leave(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (dtp_ngaygiao.Text.Trim() == "")
            {
                errorProvider1.SetError(dtp_ngaygiao, "Không được để trống 'Ngày Giao'");                
                dtp_ngaygiao.Focus();
            }
        }

        private void up_soluonggiao_Leave(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            decimal soluong_tam = up_soluonggiao.Value;
            if (soluong_tam > 1000)
            {
                errorProvider1.SetError(up_soluonggiao, "Số lượng nhập không quá 1000 !!!");
                up_soluonggiao.Focus();
                kiemtra = true;
            }
            if (soluong_tam < 1)
            {
                errorProvider1.SetError(up_soluonggiao, "Số lượng nhập không được nhỏ hơn 1 !!!");
                up_soluonggiao.Focus();
                kiemtra = true;
            }
        }
        bool kiemtra = false;
        public static bool kichhoat = false;
        private void frmGiaoHang_Activated(object sender, EventArgs e)
        {
            if (kichhoat == true)
            {
                //Load_DSSoNhap();
                dsNhapHang.Clear();
                for (int i = 0; i < bang_KhachHang.Rows.Count; i++)
                {
                    dsNhapHang.ReadXml(new StringReader(xl_SoNhap.LayDS_SoNhapChuaGiao_TheoMaKH(int.Parse(bang_KhachHang.Rows[i]["MaKH"].ToString()))));
                    if (dsNhapHang.Tables.Count > 0)
                    {
                        bang_SoNhap = dsNhapHang.Tables[0];
                    }
                }
                mccb_maphieunhap.DataSource = bang_SoNhap;
            }
        }
    }
}
